package com.nsgf.library;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.nsgf.library.data.api.APIs;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.databinding.ActivitySplashBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.photopicker.utils.PermissionsUtils;
import com.nsgf.library.ui.GotoActivity;
import com.nsgf.library.ui.page.BaseActivity;
import com.nsgf.library.ui.page.LoginActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.library.utils.SysUtil;
import com.nsgf.library.utils.UpdateService;
import com.nsgf.skjz.utils.StringUtil;

import cn.jiguang.api.utils.JCollectionAuth;
import cn.jpush.android.api.JPushInterface;

public class SplashActivity extends BaseActivity {

    StateHolder mState;
    AccountRequester mAccountRequester;

    ActivitySplashBinding mBinding;

    @Override
    protected void initViewModel() {
        mState = getActivityScopeViewModel(StateHolder.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.activity_splash, BR.vm, mState);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
        mBinding = (ActivitySplashBinding) getBinding();
        mBinding.tvSplashAppName.setText(SysUtil.getNewAppName(this));
        // 调整点二：隐私政策授权获取成功后调用
        JCollectionAuth.setAuth(this, true); //如初始化被拦截过，将重试初始化过程

        getLifecycle().addObserver(mAccountRequester);
        mAccountRequester.getVersion();
        mAccountRequester.getLibraryInfo().observe(this, responseStatus -> {
            if (200 == responseStatus.getResponseCode() && null != responseStatus.getData()) {
                PackageManager packageManager = getPackageManager();
                PackageInfo packageInfo = null;
                try {
                    packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
                    if (packageInfo.versionCode < responseStatus.getData().getVersion_code()) {

                        showUpdataVersion(SplashActivity.this,
                                responseStatus.getData().getIs_force(),
                                responseStatus.getData().getUrl(),
                                responseStatus.getData().getContent());
                        return;
                    }
                } catch (PackageManager.NameNotFoundException e) {

                    if (StringUtil.isEmpty(UserInfo.getInstance().getTokenValue())) {
                        startActivity(new Intent().setClass(SplashActivity.this, LoginActivity.class));
                    } else {
                        GotoActivity.gotoMainActivity(SplashActivity.this, UserInfo.getInstance().getActivityType());
                    }
                    finish();
                    throw new RuntimeException(e);
                }
                if (StringUtil.isEmpty(UserInfo.getInstance().getTokenValue())) {
                    startActivity(new Intent().setClass(SplashActivity.this, LoginActivity.class));
                } else {
                    GotoActivity.gotoMainActivity(SplashActivity.this, UserInfo.getInstance().getActivityType());
                }
                finish();
            } else {
                if (StringUtil.isEmpty(UserInfo.getInstance().getTokenValue())) {
                    startActivity(new Intent().setClass(SplashActivity.this, LoginActivity.class));
                } else {
                    GotoActivity.gotoMainActivity(SplashActivity.this, UserInfo.getInstance().getActivityType());
                }
                finish();
            }
        });

    }

    private Dialog dialog;

    /**
     * 版本更新弹窗
     *
     * @param is_force 是否强制更新
     * @param url      下载apk地址
     * @param content
     */
    private void showUpdataVersion(Activity context, int is_force, String url, String content) {
        dialog = new Dialog(context, R.style.dialog_style);
        View view = View.inflate(context, R.layout.dialog_updata_version, null);
        TextView textView = view.findViewById(R.id.tv_dialog_version_info);
        TextView tv_dialog_confirm = view.findViewById(R.id.tv_dialog_confirm);
        TextView tv_dialog_cancel = view.findViewById(R.id.tv_dialog_version_cancel);
        View view_link = view.findViewById(R.id.view_link);
        tv_dialog_cancel.setOnClickListener(v -> {

            if (StringUtil.isEmpty(UserInfo.getInstance().getTokenValue())) {
                startActivity(new Intent().setClass(SplashActivity.this, LoginActivity.class));
            } else {
                GotoActivity.gotoMainActivity(SplashActivity.this, UserInfo.getInstance().getActivityType());
            }
            finish();
            dialog.dismiss();
        });
        tv_dialog_confirm.setOnClickListener(v -> {

            boolean checkPermissionFirst;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                checkPermissionFirst = PermissionsUtils.checkPermissionFirst(SplashActivity.this, 10003,
                        new String[]{Manifest.permission.READ_MEDIA_IMAGES,
                                Manifest.permission.READ_MEDIA_VIDEO,
                                Manifest.permission.READ_MEDIA_AUDIO});
            } else
                checkPermissionFirst = PermissionsUtils.checkPermissionFirst(SplashActivity.this, 10003,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA});

            if (checkPermissionFirst) {
                UpdateService service = new UpdateService(context);
                // 拼接渠道下载链接地址
                service.download(APIs.BASE_URL + "appH5/app.apk", "");
                dialog.dismiss();
            }
        });
        textView.setText(content);

        if (1 == is_force) {
            tv_dialog_cancel.setVisibility(View.GONE);
            view_link.setVisibility(View.GONE);
        } else {
            view_link.setVisibility(View.VISIBLE);
            tv_dialog_cancel.setVisibility(View.VISIBLE);
        }

        dialog.setContentView(view);
        dialog.setOnDismissListener(dialog -> backgroundAlpha(context, 1f));
        dialog.setCancelable(false);
        dialog.show();
        backgroundAlpha(context, 0.6f);

    }


    public static boolean isValidFiled(String targetFiled) {

        if (!"0".equals(targetFiled) && !"".equals(targetFiled.trim())) {
            return true;
        }
        return false;
    }


}
